//
//  GKThemeController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2021/8/9.
//  Copyright © 2021 wangws1990. All rights reserved.
//
import UIKit

class GKMyThemeController: BaseConnectionController {
    private lazy var listData : [GKTheme] = []
    private var selectTheme :String{
        return moya.client.theme?.fileName ?? "defaults"
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.showNavTitle(title: "换肤")
        self.setupRefresh(scrollView: self.collectionView, options: .auto)
    }
    override func refreshData(page: Int) {
        let listFile = ["blue","red","brown","black","orange","green","purple","pink","cyan","yellow","defaults"]
        listFile.forEach { fileName in
            let model = ApiClient.getTheme(fileName)
            self.listData.append(model)
        }
        self.collectionView.reloadData()
        self.endRefresh(more: false)
    }
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.listData.count
    }
    //上下
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    //左右
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (SCREEN_WIDTH - 20)/2 - 0.1
        return CGSize(width: width, height:130)
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let item = self.listData[indexPath.row]
        let cell = GKMyThemeCell.cellForCollectionView(collectionView: collectionView, indexPath: indexPath)
        cell.theme = item
        cell.selectCell = item.fileName == self.selectTheme
        return cell
    }
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let item = self.listData[indexPath.row]
        if item.fileName == self.selectTheme {
            return
        }
        ApiClient.setTheme(item)
        NotificationCenter.default.post(name: AppThemeNotification, object:UIColor(hex:item.color))
        self.collectionView.reloadData()
    }
}
